<template>
  <div id="doctorPage">
    <!-- <a-spin :spinning="shareImportSpinning" tip="文件數據導入處理中，請耐心等待..."> -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-button type="primary" @click="handleCreate">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
      <a-dropdown>
        <a-button type="default" :loading="exportLoading">
          <template #icon>
            <ExportOutlined />
          </template>
          導出
        </a-button>
        <template #overlay>
          <a-menu @click="handleExport">
            <a-menu-item key="filteredData"> 按篩選導出 </a-menu-item>
            <a-menu-item key="allData"> 全部導出 </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>

      <!-- <a-button type="default" @click="handleImport">
            <template #icon>
              <ImportOutlined />
            </template>
            服務分成導入
          </a-button>
          <a-button type="default" @click="handleShareExport" :loading="shareExportLoading">
            <template #icon>
              <ExportOutlined />
            </template>
            服務分成導出
          </a-button>

          <input type="file" ref="excelInput" accept=".xlsx,.xls" style="display: none" @change="handleFileChange" /> -->
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'staffType'">
            <a-tag :bordered="false" color="green" v-if="record.staffType == 1"
              >合作</a-tag
            >
            <a-tag
              :bordered="false"
              color="blue"
              v-else-if="record.staffType == 2"
              >員工</a-tag
            >
            <a-tag :bordered="false" color="default" v-else>未知</a-tag>
          </template>
          <template v-if="column.dataIndex === 'currentShift'">
            <a-tag v-if="record.currentShift == 1" color="#2db7f5">全日</a-tag>
            <a-tag v-else-if="record.currentShift == 2" color="#88e8db"
              >半日</a-tag
            >
            <a-tag v-else color="default">未知</a-tag>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag
              :bordered="false"
              color="processing"
              v-if="!record.lastDate || record.hireDate <= nowDate"
              >在職</a-tag
            >
            <a-tag :bordered="false" color="error" v-else>離職</a-tag>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space :wrap="true">
              <a-button @click="handleView(record)">查看</a-button>
              <a-button @click="handleEdit(record)">編輯</a-button>
              <a-button @click="handleRight(record)">權益設置</a-button>
              <a-button @click="handleShareRule(record)">分成規則</a-button>
              <a-button type="dashed" @click="handleRecount(record)"
                >重新核算</a-button
              >
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 新建模態框 -->
    <a-modal v-model:open="showModalCreate" title="新建醫師" :footer="null">
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>

    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯醫師
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>

    <a-modal v-model:open="showModalRight" :footer="null">
      <template #title>
        醫師權益設置
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ rightFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="rightFormRef"
        :fieldConfig="rightFieldConfig"
        @submit="handleRightSubmit"
        :formData="rightFormData"
      />
    </a-modal>

    <!-- 重新核算模態框 -->
    <a-modal v-model:open="showModalRecount" :footer="null">
      <template #title>
        重新核算
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          員工編號: {{ recountStaffCode }}</a-tag
        >
      </template>
      <DynamicForm
        ref="recountFormRef"
        :fieldConfig="recountFieldConfig"
        @submit="handleRecountSubmit"
      />
    </a-modal>

    <!-- </a-spin> -->
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message } from "ant-design-vue";
import {
  PlusOutlined,
  ExportOutlined,
  ImportOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  filterFields,
  getCreteFieldConfig,
  getEditFieldConfig,
  getRightFieldConfig,
  getRecountFieldConfig,
} from "@/models/doctor";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";
import { doctorApi } from "@/api";
import { useRouter, useRoute } from "vue-router";
import type { RouteLocationRaw } from "vue-router";

const breadcrumbItems = [{ url: "", name: "醫生管理" }];
const columns = tableColumns;
const filterConfig = filterFields;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const nowDate = new Date().toISOString().slice(0, 10);

const tableData = ref([]);
const editRecordId = ref<number>(0);
const editFormData = reactive<any>({});

const fetchData = async (params?: any) => {
  loading.value = true;
  try {
    const {
      data: { list, page, limit, total },
    } = await doctorApi.getDoctorList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取醫生列表失敗", error);
  } finally {
    loading.value = false;
  }
};
const pagination = createPagination();
// 監聽路由query變化
watchRouteQuery(fetchData);

const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 新建
const showModalCreate = ref(false);
const handleCreate = async () => {
  showModalCreate.value = true;
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = await getCreteFieldConfig();
  }
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  try {
    await doctorApi.createDoctor(data);
    message.success("創建醫師成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchData(route.query);
  } catch (error) {
    console.error("創建醫師失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 編輯

const showModalEdit = ref(false);
const handleEdit = (record: any) => {
  showModalEdit.value = true;
  editRecordId.value = Number(record.id);
  Object.assign(editFormData, record);
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    await doctorApi.updateDoctor(editRecordId.value, data);
    message.success("修改醫生信息成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改醫生信息失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

const handleView = (record: any) => {
  router.push({ name: "DoctorDetail", params: { id: record.id } });
};

const showModalRight = ref(false);
const rightRecordId = ref<number>(0);
const rightFormData = reactive<any>({});
const rightFieldConfig = ref<Record<string, any>>({});
const handleRight = (record: any) => {
  showModalRight.value = true;
  if (Object.keys(rightFieldConfig.value).length === 0) {
    rightFieldConfig.value = getRightFieldConfig();
  }
  rightRecordId.value = Number(record.id);
  console.log(record.right);

  Object.assign(rightFormData, record.right);
};

const rightFormRef = ref();
const handleRightSubmit = async (data: any) => {
  console.log("formData", data);
  console.log("id", rightRecordId.value);
  try {
    await doctorApi.setDoctorRight(rightRecordId.value, data);
    message.success("設置醫師權益成功");
    showModalRight.value = false;
    // fetchData(route.query)
  } catch (error) {
    console.error("設置醫師權益失敗", error);
  } finally {
    rightFormRef.value?.resetLoading();
  }
};

const handleShareRule = (record: any) => {
  router.push({ name: "DoctorShareRule", params: { id: record.id } });
};

const handleDoctorService = (record: any) => {
  router.push({
    name: "DoctorService",
    params: { id: record.id },
    meta: { doctorData: 123 },
  } as RouteLocationRaw);
};

const exportLoading = ref(false);
// 導出
const handleExport = async ({ key }: { key: string }) => {
  let params: any = {};
  if (key === "filteredData") {
    params = { ...route.query };
    delete params.page;
    delete params.pageSize;
  }
  exportLoading.value = true;
  try {
    await doctorApi.exportDoctorList(params);
  } catch (error) {
    message.error("導出數據失敗");
  } finally {
    exportLoading.value = false;
  }
};

// const shareExportLoading = ref(false)
// // 導出醫師分成
// const handleShareExport = async () => {
//   shareExportLoading.value = true
//   try {
//     await doctorApi.exportDoctorShare()
//   } catch (error) {
//     message.error('導出分成數據失敗')
//   } finally {
//     shareExportLoading.value = false
//   }
// }

// const excelInput = ref<HTMLInputElement>(null) // 綁定文件輸入控件

// const handleImport = () => {
//   excelInput.value?.click() // 觸發文件選擇框
// }

// const shareImportSpinning = ref(false)
// 文件選擇後的處理
// const handleFileChange = async (e: Event) => {
//   shareImportSpinning.value = true
//   const file = (e.target as HTMLInputElement).files?.[0]
//   if (!file) return

//   try {
//     const formData = new FormData()
//     formData.append('file', file) // 假設後端接收的文件字段名為'file'，需與後端確認

//     // 直接上傳文件流（需後端提供接收文件的接口）
//     await doctorApi.importDoctorShare(formData)
//     message.success('已成功處理導入的文件')
//   } catch (error) {
//     // message.error('導入失敗')
//     console.error('導入失敗:', error)
//   } finally {
//     // 清空文件輸入，避免重複選擇同一文件時不觸發change事件
//     excelInput.value!.value = ''
//     shareImportSpinning.value = false
//   }
// }

// 重新核算

const showModalRecount = ref(false);
const recountFieldConfig = ref<Record<string, any>>({});
const recountStaffCode = ref("");
const recountDoctorName = ref("");
const handleRecount = (record: any) => {
  showModalRecount.value = true;
  recountStaffCode.value = record.staffCode;
  recountDoctorName.value = record.doctorName;
  if (Object.keys(editFieldConfig.value).length === 0) {
    recountFieldConfig.value = getRecountFieldConfig();
  }
};

const recountFormRef = ref();
const handleRecountSubmit = async (data: any) => {
  try {
    message.warning("預設功能，待開發中...");

    //實現待定
    // await doctorApi.updateDoctor(recountStaffCode.value, data);
    // message.success("申請重新核算成功");
    // showModalRecount.value = false;
  } catch (error) {
    console.error("申請重新核算失敗", error);
  } finally {
    recountFormRef.value?.resetLoading();
  }
};
</script>

<style scoped></style>
